package com.neusoft.neuiotms.dcom.controller.insurance;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.file.dto.FileDTO;
import com.neusoft.bizcore.file.service.FileService;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.dto.insurance.InsuranceInspectionTaskDTO;
import com.neusoft.neuiotms.dcom.dto.insurance.InsuranceRegisterTaskDTO;
import com.neusoft.neuiotms.dcom.dto.insurance.InsuranceReportTaskDTO;
import com.neusoft.neuiotms.dcom.dto.insurance.InsuranceSummaryTaskDTO;
import com.neusoft.neuiotms.dcom.service.insurance.InsuranceRegisterTaskService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "重保服务登记任务")
@RestController
@RequestMapping(value = "/api/w/insurance/register/task")
public class InsuranceRegisterTaskController {

    @Autowired
    private InsuranceRegisterTaskService taskService;
    @Autowired
    private FileService fileService;

    @ApiOperation("查询所有重保服务登记任务")
    @GetMapping
    public ResultListDTO<InsuranceRegisterTaskDTO> index(final Searchable searchable, final UserBean user) {
        return ResultListDTO.success(this.taskService.index(searchable, user));
    }

    @ApiOperation("分页查询重保服务登记任务")
    @GetMapping("/p")
    public PageResultDTO<InsuranceRegisterTaskDTO> page(final Searchable searchable, final Pageable pageable,
            final UserBean user) {
        return PageResultDTO.success(this.taskService.page(searchable, pageable, user));
    }

    @ApiOperation("更新重保服务登记任务")
    @PutMapping("/{id}")
    public ResultDTO<InsuranceRegisterTaskDTO> update(@PathVariable final Long id,
            @RequestBody final InsuranceRegisterTaskDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.taskService.update(id, dto, user));
    }

    @ApiOperation("查看重保服务登记任务")
    @GetMapping("/{id}")
    public ResultDTO<InsuranceRegisterTaskDTO> detail(@PathVariable final Long id) {
        return ResultDTO.success(this.taskService.detail(id));
    }

    @ApiOperation("查询所有重保巡检任务")
    @GetMapping("/inspection")
    public ResultListDTO<InsuranceInspectionTaskDTO> inspectionIndex(final Searchable searchable) {
        return ResultListDTO.success(this.taskService.inspectionIndex(searchable));
    }

    @ApiOperation("更新重保巡检任务")
    @PutMapping("/inspection/{id}")
    public ResultDTO<InsuranceInspectionTaskDTO> inspectionUpdate(@PathVariable final Long id,
            @RequestBody final InsuranceInspectionTaskDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.taskService.inspectionUpdate(id, dto, user));
    }

    @ApiOperation("提交重保巡检任务")
    @RequestMapping(path = "/inspection/submit/{id}", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<InsuranceInspectionTaskDTO> inspectionSubmit(@PathVariable final Long id,
            @RequestBody final InsuranceInspectionTaskDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.taskService.inspectionSubmit(id, dto, user));
    }

    @ApiOperation("查看重保巡检任务")
    @GetMapping("/inspection/{registerTaskId}/{type}")
    public ResultDTO<InsuranceInspectionTaskDTO> inspectionDetail(@PathVariable final Long registerTaskId,
            @PathVariable final String type) {
        return ResultDTO.success(this.taskService.inspectionDetail(registerTaskId, type));
    }

    @ApiOperation("查询所有每日上报任务")
    @GetMapping("/report")
    public ResultListDTO<InsuranceReportTaskDTO> reportIndex(final Searchable searchable) {
        return ResultListDTO.success(this.taskService.reportIndex(searchable));
    }

    @ApiOperation("更新每日上报任务")
    @RequestMapping(path = "/report/{id}", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<InsuranceReportTaskDTO> reportUpdate(@PathVariable final Long id,
            @RequestBody final InsuranceReportTaskDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.taskService.reportUpdate(id, dto, user));
    }

    @ApiOperation("查看每日上报任务")
    @GetMapping("/report/{id}")
    public ResultListDTO<InsuranceReportTaskDTO> reportDetail(@PathVariable final Long id) {
        return ResultListDTO.success(this.taskService.reportDetail(id));
    }

    @ApiOperation("查询所有服务总结任务")
    @GetMapping("/summary")
    public ResultListDTO<InsuranceSummaryTaskDTO> summaryIndex(final Searchable searchable) {
        return ResultListDTO.success(this.taskService.summaryIndex(searchable));
    }

    @ApiOperation("更新服务总结任务")
    @RequestMapping(path = "/summary/{id}", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<InsuranceSummaryTaskDTO> summaryUpdate(@PathVariable final Long id,
            @RequestBody final InsuranceSummaryTaskDTO dto,
            final UserBean user) {
        return ResultDTO.success(this.taskService.summaryUpdate(id, dto, user));
    }

    @ApiOperation("查看服务总结任务")
    @GetMapping("/summary/{id}")
    public ResultDTO<InsuranceSummaryTaskDTO> summaryDetail(@PathVariable final Long id) {
        return ResultDTO.success(this.taskService.summaryDetail(id));
    }

    @ApiOperation("服务总结上传文件")
    @PostMapping("/summary/upload")
    public ResultDTO<FileDTO> upload(@RequestParam("file") final MultipartFile file) {
        final FileDTO doc = this.taskService.summaryUpload(file);
        return ResultDTO.success(doc);
    }

    @ApiOperation("服务总结下载文件")
    @GetMapping("/summary/download/{fsId}")
    public void download(@PathVariable final String fsId, final HttpServletResponse response) {
        this.fileService.download(fsId, response);
    }

    @ApiOperation("服务总结删除文件")
    @DeleteMapping("/summary/files/{fsId}")
    public void deletefiles(@PathVariable final String fsId) {
        this.taskService.deleteMongoFile(fsId);
    }

    @ApiOperation("统计报表")
    @GetMapping("/stats/report")
    public PageResultDTO<Map<String, Object>> reportStats(final Pageable pageable,
            @RequestParam final Map<String, Object> params) {
        final Page<Map<String, Object>> result = this.taskService.report(pageable, params);
        return PageResultDTO.success(result);
    }

    @ApiOperation("统计报表")
    @GetMapping(value = "/stats/export")
    public void exportStats(@RequestParam final Map<String, Object> params,
            final HttpServletResponse response) {

        final Workbook workbook = this.taskService.exportReport(params);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("重保服务统计导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            InsuranceRegisterTaskController.log.error("重保服务统计导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                InsuranceRegisterTaskController.log.error("重保服务统计导出关闭流失败", e);
            }
        }
    }

}
